package com.sky.reminder;

import com.sky.exception.OrderBusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class OrderReminder {

    @Autowired
    private RedisTemplate redisTemplate;

    //定义全局变量限制催单时间
    private static final long REMINDER_LIMIT_TIME = 10;

    /**
     * 检查用户催单频率
     */
    public void checkReminderFrequency(Long userId) {
        // 构建Redis key
        String key = "order:reminder:" + userId;

        // 获取上次催单时间
        Object lastReminderTimeObj = redisTemplate.opsForValue().get(key);

        if (lastReminderTimeObj != null) {
            Long lastReminderTime = (Long) lastReminderTimeObj;
            Long currentTime = System.currentTimeMillis();

            // 计算时间差（秒）
            long timeDiff = (currentTime - lastReminderTime) / 1000;

            // 如果时间差小于限制时间，抛出异常
            if (timeDiff < REMINDER_LIMIT_TIME) {
                throw new OrderBusinessException("请勿频繁催单，请" + (REMINDER_LIMIT_TIME - timeDiff) + "秒后再试");
            }
        }
    }

    /**
     * 记录用户催单时间
     */
    public void recordReminderTime(Long userId) {
        // 构建Redis key
        String key = "order:reminder:" + userId;

        // 记录当前时间
        redisTemplate.opsForValue().set(key, System.currentTimeMillis(), REMINDER_LIMIT_TIME, TimeUnit.SECONDS);
    }
}
